package view;

import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import model.Contact;

@SuppressWarnings("serial")
public final class ContactWindow extends JFrame {

	private MainWindow mainWindow;
	private ContactWindow contactWindow;

	private JButton saveButton;
	private AddContactHandler addContactHandler;
	private ModifyContactHandler modifyContactHandler;
	private String fNameSource;
	private String lNameSource;

	private JTextField fName;
	private JTextField lName;
	private JTextField hAddress;
	private JTextField cAddress;
	private JTextArea pPhones;
	private JTextArea cPhones;
	private JTextField homePage;
	private JTextArea emails;
	private JTextField photo;
	private JTextArea others;
	private JTextArea groups;
	private JTextField insertDate;

	/**
	 * Generate a window with the contact fields.
	 * 
	 * @param mode
	 *            0=Add contact. 1=Modify contact. 2=View contact
	 */
	public ContactWindow(int mode, Contact contact, MainWindow mainWindow) {
		super("Contact.");
		this.contactWindow = this;
		this.mainWindow = mainWindow;
		this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		//this.setLocationRelativeTo(null);        
                this.setLocationByPlatform(true);
		this.setResizable(true);
		JPanel content = this.buildDisplay(mode, contact);
		this.setContentPane(content);
		this.pack();
		this.setVisible(true);
	}

	private JPanel buildDisplay(int mode, Contact contact) {

		if (mode == 0) {

			this.fName = new JTextField(20);
			this.lName = new JTextField(20);
			this.hAddress = new JTextField(20);
			this.cAddress = new JTextField(20);
			this.pPhones = new JTextArea(2, 20);
			this.cPhones = new JTextArea(2, 20);
			this.homePage = new JTextField(20);
			this.emails = new JTextArea(2, 20);
			this.photo = new JTextField(20);
			this.others = new JTextArea(2, 20);
			this.groups = new JTextArea(2, 20);
			this.insertDate = new JTextField(new Date().toString(), 20);
			this.insertDate.setEditable(false);
			this.saveButton = new JButton("Add new contact");
			this.addContactHandler = new AddContactHandler();
			this.saveButton.addActionListener(addContactHandler);

		}

		else if (mode == 1) {
			String tmpString;

			this.fName = new JTextField(contact.getfName(), 20);
			this.lName = new JTextField(contact.getlName(), 20);
			this.hAddress = new JTextField(contact.gethAddress(), 20);
			this.cAddress = new JTextField(contact.getcAddress(), 20);
			tmpString = "";
			for (String string : contact.getpPhones()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.pPhones = new JTextArea(tmpString, 2, 20);
			tmpString = "";
			for (String string : contact.getcPhones()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.cPhones = new JTextArea(tmpString, 2, 20);
			this.homePage = new JTextField(contact.getHomePage(), 20);
			tmpString = "";
			for (String string : contact.getEmails()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.emails = new JTextArea(tmpString, 2, 20);
			this.photo = new JTextField(contact.getPhoto(), 20);
			tmpString = "";

			Iterator<?> it = contact.getOthers().entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> pairs = (Map.Entry<String, String>) it
						.next();
				tmpString = tmpString.concat(pairs.getKey());
				tmpString = tmpString.concat(" ");
				tmpString = tmpString.concat(pairs.getValue());
				tmpString = tmpString.concat("\n");
			}

			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.others = new JTextArea(tmpString, 2, 20);
			tmpString = "";
			for (String string : contact.getGroups()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.groups = new JTextArea(tmpString, 2, 20);
			this.insertDate = new JTextField(
					contact.getInsertDate().toString(), 20);
			this.insertDate.setEditable(false);
			this.saveButton = new JButton("Modify contact");
			this.modifyContactHandler = new ModifyContactHandler();
			this.saveButton.addActionListener(modifyContactHandler);

			this.fNameSource = contact.getfName();
			this.lNameSource = contact.getlName();

		}

		else if (mode == 2) {
			String tmpString;

			this.fName = new JTextField(contact.getfName(), 20);
			this.fName.setEditable(false);
			this.lName = new JTextField(contact.getlName(), 20);
			this.lName.setEditable(false);
			this.hAddress = new JTextField(contact.gethAddress(), 20);
			this.hAddress.setEditable(false);
			this.cAddress = new JTextField(contact.getcAddress(), 20);
			this.cAddress.setEditable(false);
			tmpString = "";
			for (String string : contact.getpPhones()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.pPhones = new JTextArea(tmpString, 2, 20);
			this.pPhones.setEditable(false);
			tmpString = "";
			for (String string : contact.getcPhones()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.cPhones = new JTextArea(tmpString, 2, 20);
			this.cPhones.setEditable(false);
			this.homePage = new JTextField(contact.getHomePage(), 20);
			this.homePage.setEditable(false);
			tmpString = "";
			for (String string : contact.getEmails()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.emails = new JTextArea(tmpString, 2, 20);
			this.emails.setEditable(false);
			this.photo = new JTextField(contact.getPhoto(), 20);
			this.photo.setEditable(false);
			tmpString = "";

			Iterator<?> it = contact.getOthers().entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> pairs = (Map.Entry<String, String>) it
						.next();
				tmpString = tmpString.concat(pairs.getKey());
				tmpString = tmpString.concat(" ");
				tmpString = tmpString.concat(pairs.getValue());
				tmpString = tmpString.concat("\n");
			}

			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.others = new JTextArea(tmpString, 2, 20);
			this.others.setEditable(false);
			tmpString = "";
			for (String string : contact.getGroups()) {
				tmpString = tmpString.concat(string);
				tmpString = tmpString.concat("\n");
			}
			if (tmpString.length() > 0)
				tmpString = tmpString.substring(0, tmpString.length() - 1);
			this.groups = new JTextArea(tmpString, 2, 20);
			this.groups.setEditable(false);
			this.insertDate = new JTextField(
					contact.getInsertDate().toString(), 20);
			this.insertDate.setEditable(false);

		}

		JPanel displayPanel = new JPanel();
		displayPanel.setLayout(new BoxLayout(displayPanel, BoxLayout.Y_AXIS));

		JPanel rows = new JPanel();
		rows.setLayout(new BoxLayout(rows, BoxLayout.Y_AXIS));
		JPanel row = new JPanel();
		if (mode == 2) {
			ImageIcon icon = new ImageIcon(getClass().getResource(
					"/pics/".concat(contact.getPhoto().toString())));

			JLabel picture = new JLabel(icon);
			row = new JPanel();
			row.setLayout(new FlowLayout());
			row.add(picture);
			rows.add(row);
		}
		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("First name: "));
		row.add(fName);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Last name: "));
		row.add(lName);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Personal address: "));
		row.add(hAddress);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Work address: "));
		row.add(cAddress);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Personal phones: "));
		row.add(pPhones);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Work phones: "));
		row.add(cPhones);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Website: "));
		row.add(homePage);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("E-mails: "));
		row.add(emails);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Photo: "));
		row.add(photo);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Others: "));
		row.add(others);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Groups: "));
		row.add(groups);
		rows.add(row);

		row = new JPanel();
		row.setLayout(new FlowLayout());
		row.add(new JLabel("Insert date: "));
		row.add(insertDate);
		rows.add(row);

		JScrollPane scrollPane = new JScrollPane(rows);

		displayPanel.add(scrollPane);

		if (mode != 2)
			displayPanel.add(saveButton);

		return displayPanel;
	}

	private class AddContactHandler implements ActionListener {
		public synchronized void actionPerformed(ActionEvent e) {

			List<String> pPhonesList = new ArrayList<String>();
			for (String string : pPhones.getText().split(
					System.getProperty("line.separator"))) {
				pPhonesList.add(string);
			}
			List<String> cPhonesList = new ArrayList<String>();
			for (String string : cPhones.getText().split(
					System.getProperty("line.separator"))) {
				cPhonesList.add(string);
			}
			List<String> emailsList = new ArrayList<String>();
			for (String string : emails.getText().split(
					System.getProperty("line.separator"))) {
				emailsList.add(string);
			}
			Map<String, String> othersMap = new HashMap<String, String>();
			String[] othersLines = others.getText().split("\\r?\\n");

			for (String string : othersLines) {
				String[] vStrings = string.split("\\s+");
				if (vStrings[0].length() > 0 && vStrings[1].length() > 0)
					othersMap.put(vStrings[0], vStrings[1]);
			}
			List<String> groupsList = new ArrayList<String>();
			for (String string : groups.getText().split(
					System.getProperty("line.separator"))) {
				groupsList.add(string);
			}
			Date insertDate = new Date();

			mainWindow.addRow(new Contact(fName.getText(), lName.getText(),
					hAddress.getText(), cAddress.getText(), pPhonesList,
					cPhonesList, homePage.getText(), emailsList, photo
							.getText(), othersMap, groupsList, insertDate));
			contactWindow.dispose();

		}
	}

	private class ModifyContactHandler implements ActionListener {
		public synchronized void actionPerformed(ActionEvent e) {

			List<String> pPhonesList = new ArrayList<String>();
			for (String string : pPhones.getText().split(
					System.getProperty("line.separator"))) {
				pPhonesList.add(string);
			}
			List<String> cPhonesList = new ArrayList<String>();
			for (String string : cPhones.getText().split(
					System.getProperty("line.separator"))) {
				cPhonesList.add(string);
			}
			List<String> emailsList = new ArrayList<String>();
			for (String string : emails.getText().split(
					System.getProperty("line.separator"))) {
				emailsList.add(string);
			}
			Map<String, String> othersMap = new HashMap<String, String>();
			String[] othersLines = others.getText().split("\\r?\\n");

			for (String string : othersLines) {
				String[] vStrings = string.split("\\s+");
				if (vStrings[0].length() > 0 && vStrings[1].length() > 0)
					othersMap.put(vStrings[0], vStrings[1]);
			}
			List<String> groupsList = new ArrayList<String>();
			for (String string : groups.getText().split(
					System.getProperty("line.separator"))) {
				groupsList.add(string);
			}

			SimpleDateFormat formatter = new SimpleDateFormat(
					"EEEE MMMM d HH:mm:ss z yyyy", Locale.UK);
			long offset = 0;
			try {
				offset = formatter.parse(insertDate.getText()).getTime();
			} catch (ParseException e2) {
				e2.printStackTrace();
			}

			Date insertDate2 = new Date(offset);

			System.out.println(fNameSource + " " + fNameSource);
			mainWindow.updateRow(
					fNameSource,
					lNameSource,
					new Contact(fName.getText(), lName.getText(), hAddress
							.getText(), cAddress.getText(), pPhonesList,
							cPhonesList, homePage.getText(), emailsList, photo
									.getText(), othersMap, groupsList,
							insertDate2));

			contactWindow.dispose();
		}
	}

}
